package com.xiaojitui.pro;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.xiaojitui.cla.Class;

import javax.sql.DataSource;
import java.io.*;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

public class MainTask {
    public static String ip;
    public static void main(String[] args) throws Exception {
        Class cla=new Class();
        //主界面
        home(cla);
    }

    /**
     * 学生登陆界面
     * @param cla
     * @throws Exception
     */
    private static void home(Class cla) throws Exception {
        Scanner sc=new Scanner(System.in);
        while (true){
            System.out.println("================请选择操作：==================");
            System.out.println("1.登录");
            System.out.println("2.注册");
            System.out.println("3.退出");
            System.out.print("请输入：");
            int operate= sc.nextInt();
            if (operate==1){
                //登录操作
                Class inform=Login(sc,cla);
                //登陆后的界面
                if (inform.getStatus().equals("学生")){
                    //学生界面
                    stu_display(sc,inform);
                } else{
                    //老师界面
                    tea_display(sc,inform);
                }
            } else if (operate==2) {
                //注册操作
                register(sc);
            }else {
                System.out.println("拜拜了您嘞！");
                return;
            }
        }
    }

    /**
     * 教师登陆展示界面
     * @param sc
     * @param inform
     */
    private static void tea_display(Scanner sc, Class inform) {
        System.out.println("=============欢迎 "+inform.getName()+" 老师!===============");
        while (true) {
            System.out.println("请选择你的操作：");
            System.out.println("1. 查看学生信息");
            System.out.println("2. 添加学生信息");
            System.out.println("3. 修改学生信息");
            System.out.println("4. 删除学生信息");
            System.out.println("5. 学生信息导出");
            System.out.println("6. 弹幕小工具");
            System.out.println("7. 退出");
            System.out.println("请输入：");
            int operator=sc.nextInt();
            switch (operator){
                case 1:
                    select_stu();
                    break;
                case 2:
                    add_atu(sc);
                    break;
                case 3:
                    update_stu(sc,inform);
                    break;
                case 4:
                    delete_stu(sc);
                    break;
                case 5:
                    output_stu(inform);
                    break;
                case 6:
                    chart_tea(sc,inform);
                    break;
                case 7:
                    return;
            }
        }
    }

    /**
     * 教师端弹幕
     * @param sc
     * @param inform
     */
    private static void chart_tea(Scanner sc, Class inform) {
        try {
            //1. 创建socket通信管道，请求与服务端链接
            //参数一：服务端IP地址
            //参数二：服务端端口
            Socket socket=new Socket(ip,7777);
            socket.setSoTimeout(8000);
            System.out.println("正在查看同学们说的悄悄话。。。。");
            //创建一个独立的线程专门负责这个客户端的读消息
            //new ClientReaderThread(socket).start();
            //3. 从socket通信管道中得到一个字符输入流进行消息的接收
            InputStream is=socket.getInputStream();
            //4. 把字节输入流包装成字符输入流进行消息的接受
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            //5. 按照流程读取消息
            String msg;
            while ((msg=br.readLine())!=null){
                System.out.println(socket.getLocalSocketAddress()+"说: "+msg);
            }
//            //2. 从socket通信管道中得到一个字节输出流 负责发送数据
//            OutputStream os=socket.getOutputStream();
//            //3. 把低级的字节流转换为打印流
//            PrintStream ps=new PrintStream(os);
//            while (true) {
//                String msg=sc.nextLine();
//                //4. 发送消息
//                ps.println(msg);
//                ps.flush();
//            }
        } catch (IOException e) {
            System.out.println("没有人发言了");
        }
    }

    /**
     * 导出学生信息
     */
    private static void output_stu(Class inform) {
        Connection connection=connection();
        String sql="select * from manage where 身份='学生'";
        String number=null;
        String password=null;
        String name=null;
        Integer age=null;
        String sex=null;
        String status=null;
        String n="all_stu";
        File file=new File(n+".txt");
        try {
            FileWriter fw=new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw=new BufferedWriter(fw);
            PreparedStatement pstmt=connection.prepareStatement(sql);
            ResultSet resultSet = pstmt.executeQuery();
            bw.append("学号\t\t\t密码\t\t\t姓名\t\t\t年龄\t\t\t性别\t\t\t身份\r\n");
            while (resultSet.next()){
                number=resultSet.getString("学号");
                password=resultSet.getString("密码");
                name=resultSet.getString("姓名");
                age=resultSet.getInt("年龄");
                sex=resultSet.getString("性别");
                status=resultSet.getString("身份");
                inform.setNumber(number);
                inform.setPassword(password);
                inform.setName(name);
                inform.setAge(age);
                inform.setSex(sex);
                inform.setStatus(status);
                bw.append(number+"\t\t\t"+password+"\t\t\t"+name+"\t\t\t"+age+"\t\t\t"+sex+"\t\t\t"+status+"\r\n");
                //bw.append("学号：\t"+number+"\t密码：\t"+password+"\t姓名：\t"+name+"\t年龄：\t"+age+"\t性别：\t"+sex+"\t身份：\t"+status+"\r\n");
            }
            bw.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除学生信息
     * @param sc
     */
    private static void delete_stu(Scanner sc) {
        System.out.println("请输入要删除的学生学号：");
        String number=sc.next();
        Connection connection=connection();
        String sql="select * from manage where 学号=?";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setString(1,number);
            ResultSet resultSet = pstmt.executeQuery();//影响的行数
            if (resultSet.isBeforeFirst()){
                sql="delete from manage where 学号=?";
                pstmt=connection.prepareStatement(sql);
                pstmt.setString(1,number);
                pstmt.executeUpdate();
                System.out.println("删除成功！");
            }else {
                System.out.println("查不到该学生...");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改学生信息
     * @param sc
     * @param inform
     */
    private static void update_stu(Scanner sc, Class inform) {
        System.out.println("请输入要修改学生信息的学号：");
        String num=sc.next();
        Connection connection=connection();
        String sql="select * from manage where 学号=?";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setString(1,num);
            //执行
            ResultSet resultSet = pstmt.executeQuery();//影响的行数
            if (resultSet.isBeforeFirst()){
                while (resultSet.next()) {
                    String number=resultSet.getString("学号");
                    String password=resultSet.getString("密码");
                    String name=resultSet.getString("姓名");
                    int age=resultSet.getInt("年龄");
                    String sex=resultSet.getString("性别");
                    String status=resultSet.getString("身份");
                    inform.setNumber(number);
                    inform.setPassword(password);
                    inform.setName(name);
                    inform.setAge(age);
                    inform.setSex(sex);
                    inform.setStatus(status);
                }
                System.out.println("学号："+inform.getNumber());
                System.out.println("密码："+inform.getPassword());
                System.out.println("姓名："+inform.getName());
                System.out.println("年龄："+inform.getAge());
                System.out.println("性别："+inform.getSex());
                System.out.println("请输入你要该学生的信息：");
                System.out.println("1. 学号");
                System.out.println("2. 密码");
                System.out.println("3. 姓名");
                System.out.println("4. 年龄");
                System.out.println("5. 性别");
                System.out.println("请选择：");
                int operator=sc.nextInt();
                switch (operator){
                    case 1:
                        update_Number(sc,inform);
                        break;
                    case 2:
                        update_Password(sc,inform);
                        break;
                    case 3:
                        update_Name(sc,inform);
                        break;
                    case 4:
                        update_Age(sc,inform);
                        break;
                    case 5:
                        update_Sex(sc,inform);
                        break;
                    default:
                        System.out.println("输入有误。。。");
                }

            }else {
                System.out.println("不存在该学生学号。。。");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加学生
     * @param sc
     */
    private static void add_atu(Scanner sc) {
        System.out.println("请输入要添加的学生信息：");
        String number=null;
        String name=null;
        Integer age=null;
        String sex=null;
        while (true) {
            try {
                System.out.println("请输入要添加的学号：");
                number=sc.next();
                System.out.println("请输入要添加的姓名：");
                name=sc.next();
                System.out.println("请输入要添加的年龄：");
                age=sc.nextInt();
                System.out.println("请输入要添加的性别：");
                sex=sc.next();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Connection connection=connection();
            String sql="insert into manage values(?,'123456',?,?,?,'学生')";
            try {
                PreparedStatement pstmt=connection.prepareStatement(sql);
                pstmt.setString(1,number);
                pstmt.setString(2,name);
                pstmt.setInt(3,age);
                pstmt.setString(4,sex);
                //执行
                int count = pstmt.executeUpdate();//影响的行数
                //处理结果
                if (count>0){
                    System.out.println("添加成功成功！");
                    return;
                }
                System.out.println("添加失败。。。");
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 查看学生信息
     */
    private static void select_stu() {
        Connection connection=connection();
        String sql="select * from manage where 身份='学生'";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            //执行
            ResultSet resultSet = pstmt.executeQuery();//影响的行数
            //处理结果
            if (resultSet.isBeforeFirst()){
                while (resultSet.next()){
                    System.out.print("学号："+resultSet.getString("学号"));
                    System.out.print(" 密码："+resultSet.getString("密码"));
                    System.out.print(" 姓名："+resultSet.getString("姓名"));
                    System.out.print(" 年龄："+resultSet.getInt("年龄"));
                    System.out.print(" 性别："+resultSet.getString("性别"));
                    System.out.println();
                }
            }else {
                System.out.println("null");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 学生注册
     * @param sc
     */
    private static void register(Scanner sc) {
        String number=null;
        String password=null;
        String name=null;
        Integer age=null;
        String sex=null;
        while (true) {
            try {
                System.out.println("请输入注册的学号：");
                number=sc.next();
                System.out.println("请输入注册的密码：");
                password=sc.next();
                System.out.println("请输入注册的姓名：");
                name=sc.next();
                System.out.println("请输入注册的年龄：");
                age=sc.nextInt();
                System.out.println("请输入注册的性别：");
                sex=sc.next();
            } catch (Exception e) {
                System.out.println("输入信息格式不对，请重新输入。。。");
                break;
            }
            Connection connection=connection();
            String sql="insert into manage values(?,?,?,?,?,'学生')";
            try {
                PreparedStatement pstmt=connection.prepareStatement(sql);
                pstmt.setString(1,number);
                pstmt.setString(2,password);
                pstmt.setString(3,name);
                pstmt.setInt(4,age);
                pstmt.setString(5,sex);
                //执行
                int count = pstmt.executeUpdate();//影响的行数
                //处理结果
                if (count>0){
                    System.out.println("注册成功！");
                    return;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 学生登录后界面
     *
     * @param sc
     * @param inform
     */
    private static void stu_display(Scanner sc, Class inform) {
        while (true) {
            System.out.println("================请"+inform.getName()+"同学 操作：==================");
            System.out.println("1.查看个人信息");
            System.out.println("2.修改个人信息 ");
            System.out.println("3.个人信息导出");
            System.out.println("4.弹幕小工具");
            System.out.println("5.退出");
            System.out.print("请输入：");
            int option=sc.nextInt();
            switch (option){
                case 1:
                    look_Masage(inform);
                    break;
                case 2:
                    update_Masage(sc,inform);
                    return;
                case 3:
                    output_Inform(inform);
                    break;
                case 4:
                    chart(sc,inform);
                    break;
                case 5:
                    return;
                default:
                    System.out.println("输入有误。。。重新输入。。。");
            }
        }
    }

    /**
     * 弹幕
     * @param sc
     * @param inform
     */
    private static void chart(Scanner sc, Class inform) {
        try {
            //1. 创建socket通信管道，请求与服务端链接
            //参数一：服务端IP地址
            //参数二：服务端端口
            System.out.println("请输入目标ip地址：");
            String ip=IP(sc);
            Socket socket=new Socket(ip,7777);
            System.out.println("尽情的发言吧骚年！(输入666结束吐槽)");
            //创建一个独立的线程专门负责这个客户端的读消息
            //new ClientReaderThread(socket).start();
            //2. 从socket通信管道中得到一个字节输出流 负责发送数据
            OutputStream os=socket.getOutputStream();
            //3. 把低级的字节流转换为打印流
            int count=1;
            PrintStream ps=new PrintStream(os);
            String msg=sc.nextLine();
            while (!msg.equals("666")) {
                //4. 发送消息
                ps.println(msg);
                ps.flush();
                if (count++>5){
                    System.out.println("骚话太多了，禁言！");
                    return;
                }
                msg=sc.nextLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 返回学生输入的ip
     * @param sc
     * @return
     */
    private static String IP(Scanner sc){
        ip=sc.next();
        return ip;
    }

    /**
     * 导出个人信息
     * @param inform
     */
    private static void output_Inform(Class inform) {
        String name= inform.getName()+".txt";
        File file=new File(name);
        if (!file.exists()){
            try {
                file.createNewFile();
                FileWriter fw=new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw=new BufferedWriter(fw);
                bw.write(String.valueOf(inform));
                bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 修改个人信息
     * @param sc
     * @param inform
     */
    private static void update_Masage(Scanner sc, Class inform){
        while (true) {
            System.out.println("1. 修改学号/工号");
            System.out.println("2. 修改密码");
            System.out.println("3. 修改姓名");
            System.out.println("4. 修改年龄");
            System.out.println("5. 修改性别");
            System.out.println("6. 退出");
            System.out.println("请选择操作：");
            int option=sc.nextInt();
            switch (option){
                case 1:
                    update_Number(sc,inform);
                    return;
                case 2:
                    update_Password(sc,inform);
                    return;
                case 3:
                    update_Name(sc,inform);
                    break;
                case 4:
                    update_Age(sc,inform);
                    break;
                case 5:
                    update_Sex(sc,inform);
                    break;
                case 6:
                    return;
                default:
                    System.out.println("命令有误重新输入。。。");
            }
        }
    }

    /**
     * 修改性别
     * @param sc
     * @param inform
     */
    private static void update_Sex(Scanner sc, Class inform) {
        System.out.println("请输入您要修改后的性别：");
        String sex=sc.next();
        String name = inform.getName();
        Connection connection=connection();
        //定义sql
        String sql="update manage set 性别=? where 姓名=? ";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setString(1,sex);
            pstmt.setString(2,name);
            //执行
            int count = pstmt.executeUpdate();//影响的行数
            //处理结果
            if (count>0){
                System.out.println("修改成功！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改年龄
     * @param sc
     * @param inform
     */
    private static void update_Age(Scanner sc, Class inform) {
        System.out.println("请输入您要修改后的年龄：");
        int age=sc.nextInt();
        String name = inform.getName();
        Connection connection=connection();
        //定义sql
        String sql="update manage set 年龄=? where 姓名=? ";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setInt(1,age);
            pstmt.setString(2,name);
            //执行
            int count = pstmt.executeUpdate();//影响的行数
            //处理结果
            if (count>0){
                System.out.println("修改成功！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *修改后的名字
     * @param sc
     * @param inform
     */
    private static void update_Name(Scanner sc, Class inform) {
        System.out.println("请输入您要修改后的名字：");
        String name=sc.next();
        String number = inform.getNumber();
        Connection connection=connection();
        //定义sql
        String sql="update manage set 姓名=? where 学号=? ";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setString(1,name);
            pstmt.setString(2,number);
            //执行
            int count = pstmt.executeUpdate();//影响的行数
            //处理结果
            if (count>0){
                System.out.println("修改成功！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改密码
     * @param sc
     * @param inform
     */
    private static void update_Password(Scanner sc, Class inform) {
        System.out.println("请输入您要修改后的密码：");
        String password=sc.next();
        String number = inform.getNumber();
        Connection connection=connection();
        //定义sql
        String sql="update manage set 密码=? where 学号=?";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setString(1,password);
            pstmt.setString(2,number);
            //执行
            int count = pstmt.executeUpdate();//影响的行数
            //处理结果
            if (count>0){
                System.out.println("修改成功！数据发生变化请重新登录。。。");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改学号
     * @param sc
     * @param inform
     */
    private static void update_Number(Scanner sc, Class inform) {
        System.out.println("请输入您要修改后的学号：");
        String number=sc.next();
        String name = inform.getName();
        Connection connection=connection();
        //定义sql
        String sql="update manage set 学号=? where 姓名=?";
        try {
            PreparedStatement pstmt=connection.prepareStatement(sql);
            pstmt.setString(1,number);
            pstmt.setString(2,name);
            //执行
            int count = pstmt.executeUpdate();//影响的行数
            //处理结果
            if (count>0){
                System.out.println("修改成功！数据发生变化请重新登录。。。");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 连接池
     * @return
     */
    public static Connection connection(){
        Connection connection=null;
        try {
            Properties prop=new Properties();
            prop.load(new FileInputStream("src/druid.properties"));
            //获取连接词对象
            DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
            //获取数据库连接
            connection= dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 查看个人信息
     */
    private static void look_Masage(Class inform) {
        System.out.println("您的个人信息为：");
        System.out.println("学号/工号："+inform.getNumber());
        System.out.println("密码："+inform.getPassword());
        System.out.println("姓名："+inform.getName());
        System.out.println("年龄："+inform.getAge());
        System.out.println("性别："+inform.getSex());
        System.out.println("身份："+inform.getStatus());
    }

    /**
     * 登陆界面
     *
     * @param sc
     * @param cla
     * @return
     * @throws Exception
     */
    public static Class Login(Scanner sc, Class cla) throws Exception {
        //2022215071530
        //123456
        while (true) {
            System.out.println("请输入账号：");
            String na=sc.next();
            System.out.println("请输入密码：");
            String pa=sc.next();
            Connection connection=connection();
            //定义sql
            String sql = "select * from manage where 学号=? and 密码=?";
            PreparedStatement pstmt= connection.prepareStatement(sql);
            pstmt.setString(1,na);
            pstmt.setString(2,pa);
            //设置参数
            ResultSet resultSet = pstmt.executeQuery();
            while (resultSet.next()) {
                String number=resultSet.getString("学号");
                String password=resultSet.getString("密码");
                String name=resultSet.getString("姓名");
                int age=resultSet.getInt("年龄");
                String sex=resultSet.getString("性别");
                String status=resultSet.getString("身份");
                cla.setNumber(number);
                cla.setPassword(password);
                cla.setName(name);
                cla.setAge(age);
                cla.setSex(sex);
                cla.setStatus(status);
                return cla;
            }
            System.out.println("账号密码错误，请重新输入。。。");
        }
    }
}

/**
 * 接受信息的线程
 */
class ClientReaderThread extends Thread{
    private Socket socket;
    public ClientReaderThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            //3. 从socket通信管道中得到一个字符输入流进行消息的接收
            InputStream is=socket.getInputStream();
            //4. 把字节输入流包装成字符输入流进行消息的接受
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            //5. 按照流程读取消息
            String msg;
            while ((msg=br.readLine())!=null){
                System.out.println(socket.getLocalSocketAddress()+"说: "+msg);
            }
        } catch (Exception e) {
            System.out.println("服务端把你踢出去了。。。");
        }
    }
}